package com.jeesite.modules.yzw.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.modules.yzw.constant.Constant;
import com.jeesite.modules.yzw.dao.OtsIflytekOrgDao;
import com.jeesite.modules.yzw.entity.OtsIflytekOrg;
import com.jeesite.modules.yzw.entity.OtsIflytekOrgUser;
import com.jeesite.modules.yzw.entity.OtsIflytekUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jeesite.common.lang.StringUtils;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.util.HashMap;
import java.util.List;

/**
 * 同步讯飞信息
 * 1、组织机构同步到系统模块
 * 2、用户信息同步到系统模块
 * @author guohusong
 * @version 1.0
 * @date 2022/4/30 11:34
 */
@Service("syncIflytekService")
public class SyncIflytekService {
    private static final Logger logger = LoggerFactory.getLogger(SyncIflytekService.class);

    @Autowired
    private YzwClient yzwClient;
    @Autowired
    private OtsIfytekOrgService otsIfytekOrgService;
    @Autowired
    private OtsIfytekUserService otsIfytekUserService;
    @Autowired
    private OtsIfytekOrgUserService otsIfytekOrgUserService;
    @Autowired
    private OtsIflytekOrgDao otsIflytekOrgDao;

    /**
     * 全量的更新组织机构信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void queryDeptListAll() {
        try {
            //所有组织设置为无效
            otsIfytekOrgService.modifyOtsIflytekOrgStatus(new HashMap<String, Object>() {
                private static final long serialVersionUID = 1L;

                {
                    put("syncstate", Constant.Sync.SYNC_STATE_1);
                    put("status", Constant.Status.SYNC_STATUS_2);
                    put("compid", Constant.IFLYTEK_COMPID);
                }
            });
            String result = yzwClient.queryDeptList(Constant.TestData.CURRENT_USER_ID);
            handleOrgData(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 按照日期同步组织机构数据信息
     */
    public void queryDeptListByDate(String startDate) {
        // 处理同步时间
        if (StringUtils.isEmpty(startDate)) {
            startDate = otsIfytekOrgService.queryLastIflytekOrgSync();
        }
        String endDate = DateUtils.getDate("yyyy-MM-dd HH:mm:ss");
        String result = yzwClient.queryDeptListByDate(StringUtils.isEmpty(startDate) ? "2000-01-01 00:00:01" : startDate, endDate, Constant.TestData.CURRENT_USER_ID);
        handleOrgData(result);
    }

    /**
     * 解析返回的组织机构信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void handleOrgData(String result) {
        JSONObject resultObject = JSONObject.parseObject(result);
        String listStr = resultObject.getString("list");
        List<OtsIflytekOrg> otsIflytekOrgs = JSONArray.parseArray(listStr, OtsIflytekOrg.class);
        logger.info("------------开始同步组织数据数据" + otsIflytekOrgs.size() + "条---------------");
        otsIflytekOrgs.forEach(x -> {
            otsIfytekOrgService.save(x);
        });
        //查询所有未同步的机构
        List<OtsIflytekOrg> otsIflytekOrgList=otsIfytekOrgService.findOtsIflytekOrg();
        if(!otsIflytekOrgList.isEmpty()){
            //循环数据插入父级Id
            for (OtsIflytekOrg otsIflytekOrg:otsIflytekOrgList) {
                OtsIflytekOrg org=otsIflytekOrgDao.getOtsIflytekOrgById(Constant.IFLYTEK_COMPID,otsIflytekOrg.getParentid());
                if(org!=null){
                    otsIflytekOrg.setWhdcpid(String.valueOf(org.getUrcorgid()));
                }else {
                    otsIflytekOrg.setWhdcpid("0");
                }
                otsIflytekOrgDao.modifyOtsIflytekOrgByid(otsIflytekOrg);
            }
        }


    }

//    /**
//     * 将讯飞同步组织机构表同步到系统组织机构表中（定时调用）
//     * @param compid
//     * @param type   1 更新 ots_iflytek_org表
//     */
//    public void syncUrcOrg(String compid, Integer type) {
//        logger.info("------------开始更新系统管理组织数据---------------");
//        int count = otsIflytekOrgService.countOtsIflytekOrg(Constant.IFLYTEK_COMPID);
//        logger.info("------------更新系统管理组织数据" + count + "条---------------");
//        while (true) {
//            List<OtsIflytekOrgDto> iflyUserList = otsIflytekOrgService.queryIflytekOrgList(Constant.IFLYTEK_COMPID);
//            if (iflyUserList.size() == 0) {
//                break;
//            }
//
//            List<Future<Boolean>> futures = new ArrayList<Future<Boolean>>();
//            iflyUserList.forEach(x -> {
//                futures.add(syncIflytekFutureService.updateYzwOrg(x, type));
//            });
//            downFutures(futures);
//        }
//        logger.info("------------结束更新系统管理组织数据---------------");
//
//    }


    /**
     * 全量同步讯飞用户信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void queryUserListAll() {
        try {
            //所有用户设置为无效
            otsIfytekUserService.modifyOtsIflytekUserStatus(new HashMap<String, Object>() {
                private static final long serialVersionUID = 1L;

                {
                    put("syncstate", Constant.Sync.SYNC_STATE_1);
                    put("status", Constant.Status.SYNC_STATUS_2);
                    put("compid", Constant.IFLYTEK_COMPID);
                }
            });
            String result = yzwClient.queryUserList(Constant.TestData.CURRENT_USER_ID);
            handleUserData(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 按照日期同步用户数据
     */
    public void queryUserListByDate(String startDate) {
        // 处理时间
        if (StringUtils.isEmpty(startDate)) {
            startDate = otsIfytekUserService.queryLastIflytekUserSync();
        }
        String endDate = DateUtils.getDate("yyyy-MM-dd HH:mm:ss");

        // 处理数据
        String result = yzwClient.queryUserListByDate(StringUtils.isEmpty(startDate) ? "2000-01-01 00:00:01" : startDate, endDate, Constant.TestData.CURRENT_USER_ID);
        handleUserData(result);
    }

    /**
     * 处理用户数据
     * @param result
     */
    public void handleUserData(String result) {
        JSONObject resultObject = JSONObject.parseObject(result);
        String listStr = resultObject.getString("list");
        List<OtsIflytekUser> otsIflytekUsers = JSONArray.parseArray(listStr, OtsIflytekUser.class);
        logger.info("------------开始同步用户数据" + otsIflytekUsers.size() + "条---------------");
        otsIflytekUsers.forEach(x -> {
            otsIfytekUserService.save(x);
        });
    }


    /**
     * 更新同步用户系统模块用户信息（定时调用）
     * @throws Exception
     */
//    public void syncUrcUser(String comid) throws Exception {
//        logger.info("------------开始更新系统管理用户数据---------------");
//        int count = otsIflytekUserService.countOtsIflytekUser(Constant.IFLYTEK_COMPID);
//        logger.info("------------开始更新系统管理用户数据" + count + "条---------------");
//        int size = 0;
//        while (true) {
//            //每次更新1500条数据
//            List<OtsIflytekUserDto> userList = otsIflytekUserService.listOtsIflytekUserByNotSyncstate(Constant.IFLYTEK_COMPID);
//            if (userList.size() == 0) {
//                break;
//            }
//
//            List<Future<Boolean>> futures = new ArrayList<Future<Boolean>>();
//            userList.forEach(x -> {
//                futures.add(syncIflytekFutureService.updateYzwUser(x));
//            });
//            downFutures(futures);
//            size++;
//            logger.info("------------结束第" + size + "次，共计" + userList.size() + "条系统管理用户数据---------------");
//        }
//
//        logger.info("------------结束更新系统管理用户数据---------------");
//    }


    /**
     * Lx01004组织机构用户查询
     */
    @Transactional(rollbackFor = Exception.class)
    public void queryDeptUserListAll() {
        try {
            //删除所有机构用户关系
            otsIfytekOrgUserService.delOtsIflytekOrgUser(new HashMap<String, Object>() {
                private static final long serialVersionUID = 1L;

                {
                    put("compid", Constant.IFLYTEK_COMPID);
                }
            });
            String result = yzwClient.queryDeptUserList(Constant.TestData.CURRENT_USER_ID);
            handleDeptUserData(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void queryDeptUserListByDate(String startDate) {
        // 处理时间
        if (StringUtils.isEmpty(startDate)) {
            startDate = otsIfytekOrgUserService.queryLastIflytekOrgUserSync();
        }
        String endDate = DateUtils.getDate("yyyy-MM-dd HH:mm:ss");

        // 处理数据
        String result = yzwClient.queryDeptUserListByDate(StringUtils.isEmpty(startDate) ? "2000-01-01 00:00:01" : startDate, endDate, Constant.TestData.CURRENT_USER_ID);
        handleDeptUserData(result);
    }

    /**
     * 处理组织用户关系
     * @param result
     */
    @Transactional(rollbackFor = Exception.class)
    public void handleDeptUserData(String result) {
        JSONObject resultObject = JSONObject.parseObject(result);
        String listStr = resultObject.getString("list");
        List<OtsIflytekOrgUser> otsIflytekOrgUsers = JSONArray.parseArray(listStr, OtsIflytekOrgUser.class);
        otsIflytekOrgUsers.forEach(x -> {
            otsIfytekOrgUserService.addOtsIflytekOrgUser(x);
        });
    }
}
